<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\Util;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;

/**
 * 章节
 *
 * @icon fa fa-circle-o
 */
class CourseLesson extends Backend
{
    
    /**
     * CourseLesson模型对象
     * @var \app\admin\model\CourseLesson
     */
    protected $model = null;
    protected $baseUrl = 'https://live.21bmw.com/#/login';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CourseLesson;
        $this->view->assign("lessonStatusList", $this->model->getLessonStatusList());
        $this->view->assign("lessonTypeList", $this->model->getLessonTypeList());
        $this->view->assign("lessonType", $this->model->getLessonTypeList());
        $id = $this->auth->id;
        $group = Db::name('auth_group_access')->where('uid', $id)->find()['group_id'];
        $this->view->assign("group",$group);
        //todo 如果登录者是教师则去查询教师的Im账号
        if($group == '2'){

        }
    }
    /**
     * 查看
     */
    public function index($ids = '')
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $whereTwo = [];
            $courseID = input('ids');
            if(!empty($courseID)){
                $whereTwo['course_lesson.course_id'] = $courseID;
            }
            $total = $this->model
                    ->with(['course'])
                    ->where($where)
                    ->where($whereTwo)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['course'])
                    ->where($where)
                    ->where($whereTwo)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('course')->visible(['title']);
            }
            $list = collection($list)->toArray();
            foreach ($list as &$v){
                $v['live'] = 0;
                if(time() >= strtotime($v['start_time']) - 5*60 && time() <= strtotime($v['end_time'])){
                    if($v['lesson_type'] == 'live' && $v['play_status'] == 1){
                        $v['live'] = 1;
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign('courseID',$ids);
        $is_check = Db::name('course')->where('id',$ids)->field('is_check')->find()['is_check'];
        $this->assign('is_check',$is_check);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['course_id'] = input("ids");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // 查询此次插入的是第几课时
                    $result = Db::name('course_lesson')->where('course_id',$params['course_id'])->select();
                    if(empty($result)){
                        $params['lesson_id'] = 1;
                    }else{
                        $flagMax = 0;
                        foreach ($result as $k => $v){
                            if($v['lesson_id'] > $flagMax){
                                $flagMax = $v['lesson_id'];
                            }
                        }
                        $params['lesson_id'] = $flagMax + 1;
                    }
                    $params['lesson_status'] = 0;
                    // 课程表课时数量自增
                    Db::name('course')->where('id',$params['course_id'])->setInc('section_num');
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    //删除时对序号重新排序
                    $result = Db::name('course_lesson')->where('course_id',$v->course_id)->select();
                    if(Util::checkEmpty($result,'array')){
                        foreach ($result as $key => $value){
                            if($value['lesson_id'] > $v->lesson_id){
                              Db::name('course_lesson')->where('id',$value['id'])->setDec('lesson_id');
                            }
                        }
                    }
                    // 课程表课时数量自增
                    $res =  Db::name('course')->where('id',$v['course_id'])->setDec('section_num');
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    // 发布取消发布课时

    public function issue(){
        $param = input();
        $res = Db::name('course_lesson')->where('id',$param['ids'])->update(['lesson_status' => $param['type']]);
        empty($res) ? $this->error() : $this->success($param['type'] == 1 ? '发布成功' : "取消成功");
    }

    /**
     * 编辑
     */
    public function show($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * Notes:直播前的准备
     * User: XingLiangRen
     * Date: 2020/9/16
     * Time: 22:31
     */
    public function beginLive($ids = ''){

        // 拿到老师的Im账号
        $teacher = Db::name('teacher')->where('admin_id',$this->auth->id)->find();
        $teacherIm = Db::name('im')->where(['uid' => $teacher['id'],'type' => 'teacher'])->field('accid,token')->find();
        // 创建聊天室
        $courseLesson = Db::name('course_lesson')->where('id',$ids)->find();
        $hooks_data = [
            'creator' => $teacherIm['accid'],
            'name'     => $courseLesson['title'],
        ];
        $data = Hook::listen("createChatroom",$hooks_data,'',true);
        if($data['code'] == 200){
            $roomId = $data['chatroom']['roomid'];
            Db::name('course_lesson')->where('id',$ids)->update(['room_id'=> $roomId,'play_status' => 2]);
            Db::name('course')->where('id',$courseLesson['course_id'])->update(['lived_course_lesson_id' => $courseLesson['id']]);
            $url = $this->baseUrl . '?name=' . $teacherIm['accid'] . '&psd='. $teacherIm['token'] .'&roomName=' . $roomId;
            $this->success("成功",$url);
        }
         $this->error($data['desc']);
    }
}
